package top.ysez.controller;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 03实现Callable,可以有返回值,可以抛异常
 *
 * @author YsEz
 * @version V1.0.0
 * @date 2022/7/5 21:59
 */
@Slf4j
public class Thread03 {
  public static void main(String[] args) {
    FutureTask<String> futureTask3 =
        new FutureTask(
            new Callable() {
              @Override
              public Object call() throws Exception {
                System.out.println("会等4秒");
                Thread.sleep(4000);
                return "子线程3";
              }
            });
    Thread t3 = new Thread(futureTask3);
    t3.start();
    // 这里是个阻塞方法,会等待子线程返回result后,主线程财务继续执行
    try {
      String result = futureTask3.get();
      log.info("---result:" + result);
    } catch (InterruptedException | ExecutionException e) {
      log.error(e.getMessage(), e);
    }
    // 如果不是因为阻塞,这里早就打印了
    log.info("主线程结束");
  }
}
